﻿<!DOCTYPE html>
<html lang="en">
<head>
    <title>Shippety - A Simple Client for the EasyPost API</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="Scripts/jquery-2.1.1.js" type="text/javascript"></script>
    <script src="Scripts/bootstrap.min.js" type="text/javascript"></script>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-theme.min.css" rel="stylesheet" type="text/css" />
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        .vspacer20{ margin-top: 20px; }
        .vspacer40{ margin-top: 40px; }
        .hspacer20{ margin-left: 20px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='row text-muted'>
            <div class='col-xs-6'>
            <h2>Shippety</h2>
            </div>
            <div class='col-xs-6 text-right'>
                A simple client for the EasyPost API
            </div>            
        </div>
        <div class='row vspacer20'>
            <div class='col-xs-12'>
                <ul id='tabstrip' class='nav nav-tabs' role='tablist'>
                    <li class='active'><a href="#ship" data-toggle='tab'>Create Shipment</a></li>
                    <li><a href="#history" data-toggle='tab'>Shipment History</a></li>
                </ul>
            </div>
        </div>
        <div class="tab-content">
            <div class="tab-pane active" id="ship">
                <div class='row'>
                    <div class='col-xs-6'>
                        <form id='from-address' action="/v2/addresses" method="post" class='form-horizontal'>
                            <div class='row'>
                                <div class='form-group'>
                                    <label class='col-xs-2 h3 control-label'>From:</label>
                                    <div class='col-xs-9 vspacer20'>
                                        <div class="dropdown">
                                          <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
                                            Previous
                                            <span class="caret"></span>
                                          </button>
                                          <ul id='return-list' class="dropdown-menu" role="menu">
                                          </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class='row'>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='from-name'>Name</label>
                                    <div class='col-xs-10'>
                                        <textarea rows='2' class='form-control' id="from-name" name="address[name]"></textarea>
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='from-street'>Address</label>
                                    <div class='col-xs-10'>
                                        <textarea rows='2' class='form-control' id="from-street" name="address[street1]"></textarea>
                                    </div>
                                    <label class='col-xs-2 control-label' for='from-city'>
                                    </label>
                                    <div class='col-xs-6'>
                                        <input type='text' class='form-control' id="from-city" name="address[city]" placeholder="City" />
                                    </div>
                                    <div class='col-xs-2'>
                                        <input type='text' class='form-control' id="from-state" name="address[state]" placeholder="State" />
                                    </div>
                                    <div class='col-xs-2'>
                                        <input type='text' class='form-control' id="from-zip" name="address[zip]" placeholder="Zip" />
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='from-phone'>Phone</label>
                                    <div class='col-xs-4'>
                                        <input type='text' class='form-control' id='from-phone' name='address[phone]' />
                                    </div>
                                    <div class='col-xs-6 text-right'>
                                        <button type='submit' class='btn btn-primary verify-address'>
                                            Verify
                                        </button>
                                        <button type='reset' class='btn btn-default'>Clear</button>
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <div class='col-xs-2'>
                                        <input type='hidden' class='address-id' />
                                    </div>
                                    <div class='col-xs-6'>
                                        <div class='alert'>&nbsp;</div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class='col-xs-6'>
                        <form id='to-address' action="/v2/addresses" method="post" class='form-horizontal'>
                            <div class='row'>
                                <div class='form-group'>
                                    <label for='country-list' class='col-xs-2 h3 control-label'>To:</label>
                                    <div class='col-xs-7 vspacer20'>
                                        <select class='form-control' id='country-list' name='address[country]'>
                                            <option value='CA'>Canada</option>
                                            <option value='UK'>United Kingdom</option>
                                            <option selected='selected' value='US'>United States</option>
                                        </select>
                                    </div>
                                    <div class='col-xs-1 vspacer20'>
                                        <button id='customs-button' class='btn btn-default' disabled='disabled'>
                                            Customs...
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class='row'>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='to-name'>Name</label>
                                    <div class='col-xs-10'>
                                        <textarea rows='2' class='form-control' id="to-name" name="address[name]"></textarea>
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='to-street'>Address</label>
                                    <div class='col-xs-10'>
                                        <textarea rows='2' class='form-control' id="to-street" name="address[street1]"></textarea>
                                    </div>
                                    <label class='col-xs-2 control-label' for='to-city'>
                                    </label>
                                    <div class='col-xs-6'>
                                        <input type='text' class='form-control' id="to-city" name="address[city]" placeholder="City" />
                                    </div>
                                    <div class='col-xs-2'>
                                        <input type='text' class='form-control' id="to-state" name="address[state]" placeholder="State" />
                                    </div>
                                    <div class='col-xs-2'>
                                        <input type='text' class='form-control' id="to-zip" name="address[zip]" placeholder="Zip" />
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <label class='col-xs-2 control-label' for='to-phone'>Phone</label>
                                    <div class='col-xs-4'>
                                        <input type='text' class='form-control' id='to-phone' name='address[phone]' />
                                    </div>
                                    <div class='col-xs-6 text-right'>
                                        <button type='submit' class='btn btn-primary verify-address'>
                                            Verify
                                        </button>
                                        <button type='reset' class='btn btn-default'>Clear</button>
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <div class='col-xs-2'>
                                        <input type='hidden' class='address-id' />
                                    </div>
                                    <div class='col-xs-6'>
                                        <div class='alert'>&nbsp;</div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <form action='v2/parcels' method='post' class='form-inline'>
                    <div class='form-group hspacer20'>
                        <label class='control-label' for='weight'>Weight:</label>
                        <div class='input-group'>
                            <input type='text' class='form-control' id="weight" size="5" name="parcel[weight]" />
                            <span class="input-group-addon">oz</span>
                        </div>
                    </div>
                    <div id='predefined-form-group' class='form-group hspacer20'>
                        <label for='predefined' class='control-label'>Dimensions:</label>
                        <div class='input-group'>
                            <input id='predefined' class='form-control' data-name='parcel[predefined_package]' readonly='readonly' value='Parcel' />
                        </div>
                    </div>
                    <div id='dimensions-form-group' class='form-group hspacer20' style='display:none;'>
                        <label for='parcel-width' class='control-label'>Dimensions:</label>
                        <div class='input-group'>
                            <input id='parcel-width' class='form-control' data-name='parcel[width]' size="1" readonly='readonly' value='' />
                        </div>
                        <div class='input-group'>
                            <p class='form-control-static'>&times;</p>
                        </div>
                        <div class='input-group'>
                            <input id='parcel-height' class='form-control' data-name='parcel[height]' size="1" readonly='readonly' value='' />
                        </div>
                        <div class='input-group'>
                            <p class='form-control-static'>&times;</p>
                        </div>
                        <div class='input-group'>
                            <input id='parcel-length' class='form-control' data-name='parcel[length]' size="1" readonly='readonly' value='' />
                        </div>
                    </div>
                    <div class='form-group'>
                        <a class='btn btn-default' id='dimensions-link' href='#'>Change...</a>
                    </div>
                    <div id='insurance-form-group' class='form-group hspacer20'>
                        <label for='insurance-amount' class='control-label'>Insurance:</label>
                        <div class='input-group'>
                            <input id='insurance-amount' class='form-control' size='2' />
                        </div>
                    </div>
                    <div class='form-group hspacer20'>
                        <button type='submit' class='btn btn-danger' id="get-rates">Get Rates</button>
                    </div>
                    <div class='vspacer20 alert'>&nbsp;</div>
                </form>

                <table class='table'>
                    <thead>
                        <tr>
                            <th>Carrier</th>
                            <th>Service</th>
                            <th>Cost</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id='rate-table'>
                    </tbody>
                    <tfoot style='display: none;'>
                        <tr class='rate-table-template'>
                            <td>
                                <img class='carrier-image' src='' />
                                <span class='carrier-cell'></span>
                            </td>
                            <td><span class='service-cell'></span></td>
                            <td><span class='rate-cell'></span></td>
                            <td>
                                <a href="javascript:void(null);" class='btn btn-primary'>Purchase</a>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div class="tab-pane" id="history">
                <table class='table vspacer40'>
                    <thead>
                        <tr>
                            <th></th>
                            <th>Date</th>
                            <th>To</th>
                            <th>Via</th>
                            <th>Tracking</th>
                            <th>Cost</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="history-table">
                    </tbody>
                    <tfoot style="display: none;">
                        <tr class='history-table-template'>
                            <td><input type="checkbox" name="selected-id" /></td>
                            <td><span class='date-cell'></span></td>
                            <td><span class='address-cell'></span></td>
                            <td><span class='via-cell'></span></td>
                            <td><span class='tracking-cell'></span></td>
                            <td>
                                <span class='rate-cell'></span>
                                <br />
                                <span class='refund-cell'></span>
                            </td>
                            <td>
                                <a href="javascript:void(null);" class="btn btn-default btn-xs print-label">Print</a>
                                <a href="javascript:void(null);" class="btn btn-default btn-xs duplicate-label">Dupe</a>
                                <a href="javascript:void(null);" class="btn btn-default btn-xs refund-label">Refund</a>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    <div id='please-wait-overlay' class='modal'>
        <div class='modal-dialog'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <h4 class='modal-title'>Please Wait</h4>
                </div>
                <div class='modal-body'>
                    <i class="icon-spin icon-refresh"></i>
                    Loading Data...
                    <br />
                    <button id='cancel-loading' class='vspacer40 btn btn-danger'>Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <div id='customs-dialog' class='modal'>
        <div class='modal-dialog'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                        <span class="sr-only">Close</span>
                    </button>
                    <h4 class='modal-title'>Customs Information</h4>
                </div>
                <div class='modal-body'>
                    <form action='v2/customs_infos' id='customs-form'>
                        <div class='form-group'>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Description</th>
                                        <th>Qty</th>
                                        <th>Weight</th>
                                        <th>Value</th>
                                        <th>Tariff #</th>
                                        <th>Origin</th>
                                    </tr>
                                </thead>
                                <tbody id='customs-items-table'>
                                    <tr>
                                        <td>
                                            <input  size='30' name='customs_info[customs_items][0][description]' />
                                        </td>
                                        <td>
                                            <input  size='2' name='customs_info[customs_items][0][quantity]' />
                                        </td>
                                        <td>
                                            <input  size='3' name='customs_info[customs_items][0][weight]' />
                                        </td>
                                        <td>
                                            <input  size='2' name='customs_info[customs_items][0][value]' />
                                        </td>
                                        <td>
                                            <input  size='3' name='customs_info[customs_items][0][hs_tariff_number]' />
                                        </td>
                                        <td>
                                            <input  size='2' name='customs_info[customs_items][0][origin_country]' value='US' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <input  size='30'  data-name='customs_info[customs_items][1][description]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][1][quantity]' />
                                        </td>
                                        <td>
                                            <input  size='3' data-name='customs_info[customs_items][1][weight]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][1][value]' />
                                        </td>
                                        <td>
                                            <input  size='3' data-name='customs_info[customs_items][1][hs_tariff_number]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][1][origin_country]' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <input  size='30'  data-name='customs_info[customs_items][2][description]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][2][quantity]' />
                                        </td>
                                        <td>
                                            <input  size='3' data-name='customs_info[customs_items][2][weight]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][2][value]' />
                                        </td>
                                        <td>
                                            <input  size='3' data-name='customs_info[customs_items][2][hs_tariff_number]' />
                                        </td>
                                        <td>
                                            <input  size='2' data-name='customs_info[customs_items][2][origin_country]' />
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class='form-group'>
                            <label class='control-label'>Contents</label>
                            <div class='radio'>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='documents' /> Documents
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='gift' /> Gift
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='merchandise' /> Merchandise
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='returned_goods' /> Returned Goods
                                </label>
                            </div>
                            <div class='radio'>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='sample' /> Sample
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[contents_type]' value='other' /> Other:
                                </label>
                                <label class='radio-inline'>
                                    <input type='text' class='form-control' placeholder='Describe' name='customs_info[contents_explanation]' />
                                </label>
                            </div>
                        </div>
                        <div class='form-group'>
                            <label class='control-label' for='eel-pfc'>
                                EEL/PFC
                                <input type='text' class='form-control' name='customs_info[eel_pfc]' value='NOEEI 30.37(a)' />
                            </label>
                        </div>
                        <div class='form-group'>
                            <label class='control-label'>Restriction</label>
                            <div class='radio'>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[restriction_type]' value='none' /> None
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[restriction_type]' value='quarantine' /> Quarantine
                                </label>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[restriction_type]' value='sanitary_phytosanitary_inspection' /> Sanitary/Phytosanitary Inspection
                                </label>
                            </div>
                            <div class='radio'>
                                <label class='radio-inline'>
                                    <input type='radio' name='customs_info[restriction_type]' value='other' /> Other
                                </label>
                                <label class='radio-inline'>
                                    <input type='text' class='form-control' placeholder='Comments' name='customs_info[restriction_comments]' />
                                </label>
                            </div>
                        </div>
                        <hr />
                        <div class='form-group'>
                            <div class='checkbox'>
                                <label class='checkbox-inline'>
                                    <input type='checkbox' name='customs_info[customs_certify]' value='true' />
                                    I certify this information to be correct
                                </label>
                                <label class='checkbox-inline'>
                                    <input type='text' class='form-control' placeholder='Type your name' name='customs_info[customs_signer]' />
                                </label>
                                <label class='checkbox-inline'>
                                    <input type='hidden' id='customs-id' />
                                    <button type='reset' class='btn btn-default'>Clear Form</button>
                                </label>
                            </div>
                        </div>
                        <div class='alert'>&nbsp;</div>
                    </form>
                </div>
                <div class='modal-footer'>
                    <button data-dismiss='modal' class='btn btn-default'>Close</button>
                    <button id='save-customs-button' class='btn btn-primary'>Save</button>
                </div>
            </div>
        </div>
    </div>

    <div id='dimensions-dialog' class='modal'>
        <div class='modal-dialog'>
            <div class='modal-content'>
                <div class='modal-header'>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                        <span class="sr-only">Close</span>
                    </button>
                    <h4 class='modal-title'>Parcel Dimensions</h4>
                </div>
                <div class='modal-body'>
                    <div class='row'>
                        <form action='#' id='dimensions-form'>
                            <div class='col-xs-6'>
                                <h5>Select Predefined</h5>
                                <label class='control-label' for='predefined-usps'>USPS:</label>
                                <select class='form-control' id='predefined-usps'>
                                    <option></option>
                                    <option>Card</option>
                                    <option>Letter</option>
                                    <option>Flat</option>
                                    <option>Parcel</option>
                                    <option>LargeParcel</option>
                                    <option>IrregularParcel</option>
                                    <option>FlatRateEnvelope</option>
                                    <option>FlatRateLegalEnvelope</option>
                                    <option>FlatRatePaddedEnvelope</option>
                                    <option>FlatRateGiftCardEnvelope</option>
                                    <option>FlatRateWindowEnvelope</option>
                                    <option>FlatRateCardboardEnvelope</option>
                                    <option>SmallFlatRateEnvelope</option>
                                    <option>SmallFlatRateBox</option>
                                    <option>MediumFlatRateBox</option>
                                    <option>LargeFlatRateBox</option>
                                    <option>RegionalRateBoxA</option>
                                    <option>RegionalRateBoxB</option>
                                    <option>RegionalRateBoxC</option>
                                    <option>LargeFlatRateBoardGameBox</option>
                                </select>
                                <label class='control-label' for='predefined-ups'>UPS:</label>
                                <select class='form-control' id='predefined-ups'>
                                    <option></option>                            
                                    <option>UPSLetter</option>
                                    <option>UPSExpressBox</option>
                                    <option>UPS25kgBox</option>
                                    <option>UPS10kgBox</option>
                                    <option>Tube</option>
                                    <option>Pak</option>
                                    <option>Pallet</option>
                                    <option>SmallExpressBox</option>
                                    <option>MediumExpressBox</option>
                                    <option>LargeExpressBox</option>
                                </select>
                                <label class='control-label' for='predefined-fedex'>Fedex:</label>
                                <select class='form-control' id='predefined-fedex'>
                                    <option></option>                            
                                    <option>FedExEnvelope</option>
                                    <option>FedExBox</option>
                                    <option>FedExPak</option>
                                    <option>FedExTube</option>
                                    <option>FedEx10kgBox</option>
                                    <option>FedEx25kgBox</option>
                                </select>
                            </div>
                            <div class='col-xs-6'>
                                <h5>Or Enter Dimensions:</h5>
                                <div class='form-group'>
                                    <label class='control-label' for='height'>Width:</label>
                                    <div class='input-group'>
                                        <input type='text' class='form-control' id="width" />
                                        <span class="input-group-addon">inches</span>
                                    </div>
                                    <label class='control-label' for='height'>Height:</label>
                                    <div class='input-group'>
                                        <input type='text' class='form-control' id="height" />
                                        <span class="input-group-addon">inches</span>
                                    </div>
                                    <label class='control-label' for='height'>Length:</label>
                                    <div class='input-group'>
                                        <input type='text' class='form-control' id="length" />
                                        <span class="input-group-addon">inches</span>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class='modal-footer'>
                    <button data-dismiss='modal' class='btn btn-default'>Close</button>
                    <button id='save-dimensions-button' class='btn btn-primary'>Save</button>
                </div>
            </div>
        </div>
    </div>

    <div style='display:none;'>
        <form action='v2/shipments' method='post' id='get-rate-form'>
            <input type='hidden' id='to-address-id' name='shipment[to_address][id]' />
            <input type='hidden' id='from-address-id' name='shipment[from_address][id]' />
            <input type='hidden' id='parcel-id' name='shipment[parcel][id]' />
            <input type='hidden' id='customs-info-id' name='shipment[customs_info][id]' />
        </form>
        <form action='v2/shipments/{id}/buy' method='post' id='buy-postage-form'>
            <input type='hidden' id='rate-id' name='rate[id]' />
            <input type='hidden' id='insurance' data-name='insurance' />
        </form>
        <iframe style='height: 600px; width: 100%;' id='label-frame'></iframe>
    </div>

    <script type="text/javascript">
    var easyPostHost = '/easypost.ashx/'; // include trailing slash

    $(function () {
        $('#label-frame').contents().find('head').append('<link href="Content/layouts.css" rel="stylesheet" />');

        getEasyPost('v2/shipments')
        .done(function (shipmentsJson) {
            console.log(shipmentsJson);
            var ids = [];
            $.each(shipmentsJson.shipments.reverse(), function (i, shipmentJson) {
                addHistoryRow(shipmentJson);
                var returnId = shipmentJson.from_address.id;
                var $returnList = $('#return-list');
                if (ids.indexOf(returnId) < 0) {
                    ids.push(returnId);
                    $returnList.append(
                        $('<li />')
                        .append($('<a />')
                        .attr({ href: '#', tabindex: '-1' })
                        .text(addressToString(shipmentJson.from_address))
                        .click(function (event) {
                            event.preventDefault();
                            var $form = $('#from-address');
                            $form.find('.alert').removeClass('alert-danger').addClass('alert-success').text('Verified');
                            setAddress($form, shipmentJson.from_address);
                        }))
                    );
                }
            });
        });

        $('.verify-address').click(function (event) {
            event.preventDefault();
            var $form = $(this).closest('form');
            var $addressid = $form.find('.address-id');
            $addressid.val('');
            var $alert = $form.find('.alert')
            $alert.removeClass('alert-success alert-danger').text('');
            postEasyPost($form)
            .done(function (addressJson) {
                console.log(addressJson);
                var intl = $('#country-list').val() != 'US';
                if (intl) {
                    $form.find('.address-id').val(addressJson.id);
                    $alert.addClass('alert-success').text('International Address');
                }
                else {
                    getEasyPost($form.attr('action') + '/' + addressJson.id + '/verify')
                    .done(function (verifiedJson) {
                        console.log(verifiedJson);
                        if (verifiedJson.Message)
                            $alert.addClass('alert-danger').text(json.Message);
                        else if (verifiedJson.IsMissingInfo)
                            $alert.addClass('alert-danger').text('Missing Info');
                        else {
                            $alert.addClass('alert-success').text('Verified');
                            setAddress($form, verifiedJson.address);
                        };
                    })
                    .fail(function (xhr) {
                        $alert.addClass('alert-danger').text(xhr.responseText);
                    });
                }
            })
            .fail(function (xhr) {
                $alert.addClass('alert-danger').text(xhr.responseText);
            });
        });
        $('#from-address, #to-address').on('reset', function () {
            var $form = $(this).closest('form');
            $form.find('.address-id').val('');
            $form.find('.alert').removeClass('alert-success alert-danger').text('');
            var $countryList = $form.find('#country-list');
            if ($countryList.length) {
                $('#customs-form').find('[type=reset]').click();
                $countryList.change();
            }
        })
        .find(':input').change(function () {
            var $form = $(this).closest('form');
            var id = $form.find('.address-id').val(),
                name = $form.find('[name="address[name]"]').val(),
                street = $form.find('[name="address[street1]"]').val(),
                city = $form.find('[name="address[city]"]').val(),
                state = $form.find('[name="address[state]"]').val(),
                zip = $form.find('[name="address[zip]"]').val();
            if ((name && street && ((city && state) || zip)) || id) {
                $form.find('.verify-address').click();
            }
        });
        $('#get-rates').click(function (event) {
            event.preventDefault();
            var $tbl = $('#rate-table').find('tr').remove();
            var $form = $(this).closest('form');
            var $alert = $form.find('.alert');
            $alert.removeClass('alert-success alert-danger').text('');
            var fromid = $('#from-address .address-id').val();
            var toid = $('#to-address .address-id').val();
            var weight = $('#weight').val();
            var customsid = $('#customs-id').val();
            var intl = $('#country-list').val() != 'US';
            var insure = $('#insurance-amount').val();
            if (!fromid || !toid || !weight || (intl && !customsid)) {
                var msg = 'Please provide ';
                if (!fromid) msg += 'a valid From address, ';
                if (!toid) msg += 'a valid To address, ';
                if (!weight) msg += 'a valid weight, ';
                if (intl && !customsid) msg += 'a valid customs form, ';
                msg += 'and then try again.';
                $alert.addClass('alert-danger').text(msg);
                return;
            }
            $('#please-wait-overlay').modal('show');
            postEasyPost($form)
            .done(function (parcelJson) {
                console.log(parcelJson);
                var $getRateForm = $('#get-rate-form');
                $('#from-address-id').val(fromid);
                $('#to-address-id').val(toid);
                $('#parcel-id').val(parcelJson.id);
                $('#customs-info-id').val(customsid || '');
                if (insure)
                    $('#insurance').val(insure).attr('name', $('#insurance').attr('data-name'));
                else
                    $('#insurance').val('').removeAttr('name');
                postEasyPost($getRateForm)
                .done(function (shipmentJson) {
                    console.log(shipmentJson);
                    addRateRows($form, shipmentJson);
                    if (shipmentJson.messages.length) {
                        var html = '';
                        $.each(shipmentJson.messages, function (i, item) { html += item.carrier + ': ' + item.message + '<br />'; });
                        $alert.addClass('alert-danger').html(html);
                    }
                })
                .fail(function (xhr) {
                    $alert.addClass('alert-danger').text(xhr.responseText);
                })
                .always(function (xhr) {
                    $('#please-wait-overlay').modal('hide');
                });
            })
            .fail(function (xhr) {
                $alert.addClass('alert-danger').text(xhr.responseText);
                $('#please-wait-overlay').modal('hide');
            });
        });
        $('#country-list').change(function () {
            if ($(this).val() == 'US') {
                $('#customs-button').attr('disabled', 'disabled');
            }
            else {
                $('#customs-button').removeAttr('disabled');
            }
        });
        $('#customs-button').click(function () {
            event.preventDefault();
            $('#customs-dialog').modal('show');
        });
        $('#save-customs-button').click(function (event) {
            event.preventDefault();
            var $form = $('#customs-form');
            var $alert = $form.find('.alert').removeClass('alert-danger').val(' ');
            $('#customs-items-table :input').each(function (i, item) {
                var $item = $(item);
                if (item.hasAttribute('data-name') && $item.val()) {
                    $item.attr('name', $item.attr('data-name'));
                }
            });
            postEasyPost($form)
            .done(function (customsJson) {
                console.log(customsJson);
                $('#customs-id').val(customsJson.id);
                $('#customs-dialog').modal('hide');
            })
            .fail(function (xhr) {
                $alert.addClass('alert-danger').val(xhr.responseText);
            });
        });
        $('#customs-form').on('reset', function () { $('#customs-id').val(''); });
        $('#dimensions-link').click(function (event) {
            event.preventDefault();
            $('#dimensions-dialog').modal('show');
        });
        $('#save-dimensions-button').click(function (event) {
            event.preventDefault();
            var dims = [$('#width').val(), $('#height').val(), $('#length').val()];
            var pre = $('#predefined-fedex').val() || $('#predefined-ups').val() || $('#predefined-usps').val();
            console.log(dims);
            console.log(pre);
            if (dims[0] && dims[1] && dims[2]) {
                $('#predefined-form-group').hide().find(':input').val('').removeAttr('name');
                $('#dimensions-form-group').show().find(':input')
                .attr('name', function () { return $(this).attr('data-name'); })
                .val(function (i) { return dims[i]; });
            }
            else if (pre) {
                $('#dimensions-form-group').hide().find(':input').val('').removeAttr('name');
                $('#predefined-form-group').show().find(':input').val(pre)
                .attr('name', function () { return $(this).attr('data-name'); });
            }
            $('#dimensions-dialog').modal('hide');
        });
    });
    function postEasyPost($form, urlId) {
        var url = $form.attr('action');
        if (url && url.charAt(0) == '/') url = url.slice(1);
        url = easyPostHost + url;
        if (url.indexOf('{') >= 0) url = url.replace('{id}', urlId);
        return $.post(url, $form.serialize(), null, 'json');
    }
    function getEasyPost(url) {
        if (url && url.charAt(0) == '/') url = url.slice(1);
        url = easyPostHost + url;
        return $.getJSON(url);
    }
    function setAddress($form, json) {
        $form.find('.address-id').val(json.id);
        var name = json.name;
        if (json.Company) name += '\n' + json.company;
        $form.find('[name="address[name]"]').val(name);
        var addr = json.street1;
        if (json.Street2) addr += '\n' + json.street2;
        $form.find('[name="address[street1]"]').val(addr);
        $form.find('[name="address[city]"]').val(json.city);
        $form.find('[name="address[state]"]').val(json.state);
        $form.find('[name="address[zip]"]').val(json.zip);
        var $phone = $form.find('[name="address[phone]"]');
        if ($phone.length) $phone.val(json.phone);
    }
    function addRateRows($form, shipmentJson) {
        $.each(shipmentJson.rates, function (i, rateJson) {
            var $tbl = $('#rate-table');
            var $row = $('.rate-table-template').clone().removeClass('rate-table-template');
            $tbl.append($row);
            $row.find('.carrier-image').attr('src', 'images/' + rateJson.carrier + '.gif');
            $row.find('.carrier-cell').text(rateJson.carrier);
            $row.find('.service-cell').text(rateJson.service);
            $row.find('.rate-cell').text(rateJson.rate);
            $row.find('a').click(function () {
                $buyPostageForm = $('#buy-postage-form');
                $('#rate-id').val(rateJson.id);
                postEasyPost($buyPostageForm, shipmentJson.id)
                .done(function (lblJson) {
                    console.log(lblJson);
                    $tbl.find('tr').remove();
                    $('#tabstrip a[href="#history"]').click();
                    shipmentJson.postage_label = lblJson.postage_label;
                    shipmentJson.selected_rate = rateJson;
                    shipmentJson.tracking_code = lblJson.tracking_code;
                    addHistoryRow(shipmentJson).find('.print-label').click();
                })
                .fail(function (xhr) {
                    $form.find('.alert').addClass('alert-danger').text(xhr.responseText);
                });
            });
        });
    }
    function addHistoryRow(shipmentJson) {
        var $tbl = $('#history-table');
        var $row = $('.history-table-template').clone().removeClass('history-table-template');
        $tbl.prepend($row);
        var dt = new Date(shipmentJson.created_at);
        $row.find('.date-cell').html(dt.toLocaleDateString() + '<br />' + dt.toLocaleTimeString());
        $row.find('.address-cell').html(addressToString(shipmentJson.to_address).replace('\n', '<br />'));
        $row.find('.via-cell').html(shipmentJson.selected_rate.carrier + '<br />' + shipmentJson.selected_rate.service);
        $row.find('.rate-cell').html(shipmentJson.selected_rate.rate);
        $row.find('.refund-cell').html(shipmentJson.refund_status);
        $row.find('.tracking-cell').html(shipmentJson.tracking_code + '<br />' + shipmentJson.status);
        $row.find('.print-label').click(function () {
            $('#please-wait-overlay').modal('show');
            var $iframe = $('#label-frame');
            $iframe.contents().find('body').empty().append(
                $('<img />')
                .attr('src', shipmentJson.postage_label.label_url)
                .addClass('size-' + shipmentJson.postage_label.label_size)
                .load(function () {
                    $('#please-wait-overlay').modal('hide');
                    var iframe = $iframe.get(0);
                    iframe.contentWindow.focus();
                    iframe.contentWindow.print();
                })
            );
        });
        $row.find('.duplicate-label').click(function () {
            fullReset();
            setAddress($('#from-address'), shipmentJson.from_address);
            setAddress($('#to-address'), shipmentJson.to_address);
            $('#tabstrip a[href="#ship"]').click();
        });
        var refundButton = $row.find('.refund-label');
        if (!shipmentJson.refund_status) {
            refundButton.click(function () {
                getEasyPost('v2/shipments/' + shipmentJson.id + '/refund')
                .done(function (refundJson) {
                    $row.find('.refund-cell').html(refundJson.refund_status);
                    refundButton.attr('disabled', 'disabled');
                });
            });
        }
        else {
            refundButton.attr('disabled', 'disabled');
        }
        return $row;
    }
    function fullReset() {
        $('#from-address').find('button[type=reset]').click();
        $('#to-address').find('button[type=reset]').click();
        $('#weight').val('');
        $('#rate-table tr').remove();
    }
    function addressToString(addressJson) {
        var s = addressJson.name;
        if (addressJson.Company) s += '\n' + addressJson.company;
        s += '\n' + addressJson.street1;
        if (addressJson.Street2) s += '\n' + addressJson.street2;
        s += '\n' + addressJson.city + ' ' + addressJson.state + ' ' + addressJson.zip;
        return s;
    }
    </script>
</body>
</html>
